package com.ndood.agent.controller.user;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ndood.agent.core.constaints.AgentErrCode;
import com.ndood.agent.core.exception.AgentException;
import com.ndood.agent.core.web.tools.SessionUtils;
import com.ndood.agent.pojo.comm.vo.AgentResultVo;
import com.ndood.agent.service.user.AccountPasswordService;

/**
 * 账户密码管理
 */
@Controller
public class AccountPasswordController {
	
	@Autowired
	private SessionUtils sessionUtils;
	
	@Autowired
	private AccountPasswordService accountPasswordService;
	
	@GetMapping("/user/account/password")
	public String toPassword(){
		return "user/account/password/account_password";
	}
	
	@PostMapping("/user/account/password/update")
	@ResponseBody
	public AgentResultVo updatePassword(String old_password, String new_password, String reply_password) throws AgentException {
		
		// Step1: 参数校验
		if(StringUtils.isBlank(old_password)||StringUtils.isBlank(new_password)||StringUtils.isBlank(reply_password)){
			throw new AgentException(AgentErrCode.ERR_PARAM, "请求参数不能为空");
		}
		if(!new_password.equals(reply_password)) {
			throw new AgentException(AgentErrCode.ERR_PARAM, "两次输入的密码不一致");
		}
		
		// Step2: 修改密码
		UserDetails userInfo = sessionUtils.getLoginUserInfo();
		if(userInfo==null) {
			throw new AgentException(AgentErrCode.ERR_OTHER, "用户未登录");
		}
		
		String userId = userInfo.getUsername();
		accountPasswordService.changePassword(userId, old_password, new_password);
		return AgentResultVo.ok().setMsg("修改密码成功，建议退出后重新登录试试");
		
	}
}
